import com.googlecode.linkmein.domain.Employees
import com.googlecode.linkmein.domain.MSN
import com.googlecode.linkmein.domain.Result
import com.googlecode.linkmein.service.FetchEmployeeService
import grails.converters.JSON
import javax.servlet.http.HttpServletResponse

class MsnController {
  FetchEmployeeService fetchEmployeeService
  def allowedMethods = [invite: 'POST', login: 'POST', index: 'GET', friends : 'GET']

  def beforeInterceptor = {
      if (!session.getAttribute("gmail")){
          flash["error"] = "Please login with your google account and make sure your google account is in our list."
          redirect(uri: "/error.gsp")
          return false
      }
  }

  def login = {
    MSN msn = MSN.get(params.name, params.password);
    Result result = msn.login();
    if (result.isSuccess()) {
      session.setAttribute("msn", msn);
      redirect(controller: 'workmates', action: index)
    } else {
      render(view: 'index')
    }
  }

  def invite = {
    MSN msn = session.getAttribute("msn")
    if (msn == null) {
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED, 'Not logged in');
      return;
    }
    Employees employees = fetchEmployeeService.getEmployees();
    Result result = msn.inviteFriend(employees.findByMsnId(params.id));
    if (result.isSuccess()) {
      response.sendError(HttpServletResponse.SC_OK, 'added successful');
    } else {
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 'failed to add');
    }
  }

  def friends = {
    MSN msn = session.getAttribute("msn")
    if (msn == null) {
      render contentType: 'text/plain', text: '[]'
    } else {
      render contentType: 'text/plain', text: msn.getFriends() as JSON
    }
  }

  def index = {
    render(view: 'index')
  }
}
